<template>
    <!-- 删除或修改生产物品对话框 -->
    <el-dialog :title="pd.title" v-model="pd.open" width="1300px" append-to-body>
          <el-form ref="bomRef" :model="pd.form" :rules="pd.rules" label-width="80px">
            <el-row>
            <el-col :span="6">
              <el-form-item label="物品名称" prop="code" width="80px">
                <ProductSearch :title="productSearchParam.title" :isSingle="productSearchParam.isSingle"
                 :dataText="pd.form.name"  :params="{ isProduce: 1 }"
                 @ok="productSearchSelect">
                </ProductSearch>

                 <!-- <el-select ref="productLineCode" v-model="pd.form.productCode" @click="getWmsProductLineCode()" placeholder="请输入物品编码" clearable>
                      <el-option  
                      v-for="productLine in pd.productLine"
                      :key="productLine.code"
                      :label="productLine.code"
                      :value="productLine.code"
                    />
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="启用" prop="enableFlag">
                <el-switch v-model="pd.form.enableFlag" active-value="0" inactive-value="1"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" v-show="pd.operation===1" plain icon="Plus" @click="submitForm" v-hasPermi="['wms:bom:add']">保存物品</el-button>
            </el-col>  
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAddWmsBomLine" v-hasPermi="['wms:bom:add']">新增子行</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="pdLine.multiple" @click="handleDelWmsBomLine()" v-hasPermi="['wms:bom:remove']">删除子行</el-button>
            </el-col>
            <el-col :span="1.5" >
                <el-button icon="Refresh" @click="getBomLineList">刷新</el-button>
            </el-col>
        </el-row>

        <el-table 
        v-loading="pdLine.loading"
        :data="pdLine.wmsBomLineList" 
        @selection-change="handleWmsBomLineSelectionChange" 
        row-key="productId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >

        <el-table-column type="selection" width="40" align="center" />``
            <el-table-column label="上级编码" align="center" prop="productId" width="120"/>
            <el-table-column label="物品子码" prop="subProductId" align="center" width="180"/>
            <el-table-column label="用量" prop="quantity" align="center" width="70"/>
            <el-table-column label="是否启用" prop="enableFlag" align="center" width="80">
                <template #default="scope">
                    <dict-tag :options="sys_is" :value="scope.row.enableFlag"/>
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center" width="90"/>
            <el-table-column label="创建者" prop="createBy" align="center" width="100"/>
            <el-table-column label="创建时间" prop="createTime" align="center" width="155"/>
            <el-table-column label="更新者" prop="updateBy" align="center" width="100"/>
            <el-table-column label="更新时间" prop="updateTime" align="center" width="155"/>

            <el-table-column fixed="right" width="170" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
                <el-button link type="primary" icon="Plus" @click="handleAddWmsBomLine(scope.row)" v-hasPermi="['wms:bom:edit']">新增</el-button>
                <el-button link type="primary" icon="Edit" @click="handleEditWmsBomLine(scope.row)" v-hasPermi="['wms:bom:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelWmsBomLine(scope.row)" v-hasPermi="['wms:bom:remove']">删除</el-button>
            </template>
        </el-table-column>
        </el-table>

        <template #footer>
        <div class="dialog-footer">
            <el-button v-show="pd.operation === 2" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="pd.open = false">取 消</el-button>
        </div>
        </template>
    </el-dialog>


        

    <!-- 添加或修改子数据项 -->
      <el-dialog :title="pdLine.title" v-model="pdLine.open" width="700px" append-to-body>
        <el-form ref="bomLineRef" :model="pdLine.form" :rules="pdLine.rules" label-width="80px">
            <el-row>
            <el-col :span="15">
                <el-form-item label="物品子码" prop="subProductId" >
                    <ProductSearch :title="材料查找" :isSingle="true" :dataText="pdLine.form.name"
                    :params="{ isMaterial: 1 }"
                     @ok="productSearchSelect">
                    </ProductSearch>
                    <!-- <el-input type="number" v-model="pdLine.form.subProductId"  placeholder="请输入子码" clearable /> -->
                </el-form-item>     
            </el-col>
            </el-row>
            <el-row>
            <el-col :span="8">
                <el-form-item label="用量" prop="quantity" >
                    <el-input type="number" min="0.0" step="0.1" v-model="pdLine.form.quantity"  placeholder="请输入数量" clearable/>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="启用" prop="enableFlag">
                    <el-switch v-model="pdLine.form.enableFlag" active-value="0" inactive-value="1"></el-switch>
                </el-form-item>
            </el-col>
            </el-row>
            <el-row>
            <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                <el-input v-model="pdLine.form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitLineForm">确 定</el-button>
                <el-button @click="pdLine.open = false">取 消</el-button>
            </div>
        </template>
      </el-dialog>

  <!-- bom_process关联对话框(添加和查看数据) -->
        <el-dialog :title="pdBP.title" v-model="pdBP.open" width="1200px" append-to-body>
          <el-form ref="BomProcessRef" :model="pdBP.form" :rules="pdBP.rules" label-width="80px">
            <el-row>
            <el-form-item label="物品编码" v-show="false" prop="productId">
              <el-input v-model="pdBP.form.productId" />
            </el-form-item> 
            <el-col :span="6">
            <el-form-item label="物品名称" prop="name">
              <el-input v-model="pdBP.form.name"  disabled="disabled" placeholder="请输入物品编码" />
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="顺序" prop="orderNum">
              <el-input v-model="pdBP.form.orderNum" type="number" placeholder="请输入顺序" />
            </el-form-item>
            </el-col>
            </el-row>
            <el-row>
            <el-col :span="6">
            <el-form-item label="工序" prop="processId">
            <ProcessSearch   @selectd="processSearchSelect" :inputText="pdBP.form.processName">
            </ProcessSearch>
              <!-- <el-input v-model="pdBP.form.processId"   placeholder="请输入工序" /> -->
            </el-form-item>
            </el-col>
            <el-col :span="6">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-switch v-model="pdBP.form.enableFlag" active-value="0" inactive-value="1"></el-switch>
            </el-form-item>
            </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pdBP.form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>

            <el-table 
            v-loading="pdBP.loading"
            :data="pdBP.BomProcessList" 
            row-key="orderNum"
            >
                <el-table-column label="工序顺序" align="center" prop="orderNum" width="100"/>
                <el-table-column label="工序名称" prop="processName" align="center" width="120"/>
                <el-table-column label="是否启用" prop="enableFlag" align="center" width="90">
                    <template #default="scope">
                        <dict-tag :options="sys_is" :value="scope.row.enableFlag"/>
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" align="center" width="120"/>
                <el-table-column label="创建者" prop="createBy" align="center" width="100"/>
                <el-table-column label="创建时间" prop="createTime" align="center" width="165"/>
                <el-table-column label="更新者" prop="updateBy" align="center" width="100"/>
                <el-table-column label="更新时间" prop="updateTime" align="center" width="165"/>

                <el-table-column fixed="right" width="170" label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleEditBomProcessLine(scope.row)" v-hasPermi="['wms:bom:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelBomProcessLine(scope.row)" v-hasPermi="['wms:bom:remove']">删除</el-button>
                </template>
            </el-table-column>
            </el-table>


          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitBPForm">确 定</el-button>
              <el-button @click="pdBP.open = false">取 消</el-button>
            </div>
          </template>
        </el-dialog>


        <!-- bom_process关联对话框(修改) -->
            <el-dialog :title="pdBPLine.title" v-model="pdBPLine.open" width="600px" append-to-body>
              <el-form ref="BomProcessLineRef" :model="pdBPLine.form" :rules="pdBPLine.rules" label-width="80px">
            
                <el-form-item label="顺序" prop="orderNum" >
                  <el-input v-model="pdBPLine.form.orderNum" type="number" placeholder="请输入顺序"  style="width: 200px" />
                </el-form-item>
               
                <el-form-item label="工序" prop="processId">
                <ProcessSearch   @selectd="processSearchSelect" :inputText="pdBPLine.form.processName">
                </ProcessSearch>
                  <!-- <el-input v-model="pdBP.form.processId"   placeholder="请输入工序" /> -->
                </el-form-item>
               
                <el-form-item label="是否启用" prop="enableFlag">
                  <el-switch v-model="pdBPLine.form.enableFlag" active-value="0" inactive-value="1"></el-switch>
                </el-form-item>
                
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="pdBPLine.form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
              </el-form>

              <template #footer>
                <div class="dialog-footer">
                  <el-button type="primary" @click="submitBPLineForm">确 定</el-button>
                  <el-button @click="pdBPLine.open = false">取 消</el-button>
                </div>
              </template>
            </el-dialog>
</template>

<script setup name="BomCurd">
import { bomGetList,bomGetLineList, delBom, addBom, editBom,addLine,editLine,delLine, getBom } from "@/api/wms/bom";
import { productGetList } from "@/api/wms/product"
import { getCurrentInstance, reactive } from "vue";
const { proxy } = getCurrentInstance();
const { sys_is } = proxy.useDict('sys_is')
const emit = defineEmits(["ok"]);
import ProductSearch from "@/views/wms/product/search"

import {addBomProcess, listBomProcess, editBomProcess, delBomProcess } from "@/api/wms/process";
import ProcessSearch from "@/views/wms/process/search"
import { rowContextKey } from "element-plus";


const pd = reactive({
    bomList: [],
    open: false,
    loading: true,
    title: "",
    form: {},
    productId: null,
    productLine: [],
    operation: 0,
    bomOptions: [],
    queryParams: {
        productCode: null,
        enableFlag: "0",
        code: null,
        pageSize: 100,
    },
    rules: {
        productCode: [
            { required: true, message: "物品编码不能为空", trigger: "blur" }
        ],        
    },
});
// 表单重置
function reset() {
    pd.form = {
        productId: null,
        productCode: null,
        enableFlag: "0",
        remark: null,
        name: null  
    };
    proxy.resetForm("bomRef");
    proxy.resetForm("bomLineRef");
}
/** 提交按钮 */
async function submitForm() {
    // proxy.$refs["bomRef"].validate(async valid =>{
    //     if (valid) {
    //         if (pd.operation == 1) {
    //             await addBom(pd.form).then(response => {
    //                 proxy.$modal.msgSuccess("新增成功");
    //             });
    //         } else if (pd.operation == 2) {
    //             await editBom(pd.form).then(response => {
    //                 proxy.$modal.msgSuccess("修改成功");
    //             });
    //         }
    //     }else {
    //         proxy.$modal.msgWarning("请完整填完信息");
    //         return;
    //     }
    debugger
        if (pd.operation == 1&&pd.form.name != null) {
            await addBom(pd.form).then(response => {
                proxy.$modal.msgSuccess("物品新增成功");
            })
            await bomGetList(pd.queryParams).then(res => {
                    pd.bomList = res.data
                    pd.form.productId = pd.bomList[pd.bomList.length - 1].productId}); 
                    pdLine.form.productId = pd.form.productId 
                         
        }else if (pd.operation == 2 ) {
               if(pd.form.productId == pd.form.oldProductId){
                 pd.open = false
                 proxy.$modal.msgSuccess("物品未做修改");
               }else{
                await editBom(pd.form).then(response => {
                    proxy.$modal.msgSuccess("物品修改成功");
                });
               }  
            } else {
            proxy.$modal.msgWarning("请完整填完物品信息");
            return;
        }
        emit("ok")
        getBomLineList()
    }
    
    pd.open = false;

/** 新增按钮操作 */
function add() {
    reset();
    pd.form = { ...pd.form }
    pd.title = "添加生产物品"
    pd.operation = 1
    pd.open = true
    pdLine.wmsBomLineList = []
    pdLine.loading =false
}
/** 修改按钮操作 */
function update(row) {
    debugger
    reset();
    pd.form = { ...pd.form, ...row }
    pd.open = true
    pd.title = "修改生产物品"
    pd.operation = 2
    pd.form.name = row.name
    pdLine.form.productId = row.productId
    pd.form.oldProductId = row.productId
    getBomLineList()
}
/** 删除按钮操作 */
function del(ids) {
    pd.operation = 3
    proxy.$modal.confirm('是否确认删除生产物品编号为"' + ids + '"的数据项？').then(function () {
        return delBom(ids);
    }).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        emit("ok")
    }).catch(() => { });
}

const pdLine = reactive({
    open: false,
    ids: [],
    loading: true,
    title: "",
    form: {},
    wmsBomLineList: [],
    multiple: true,
    operation: 0,
    queryParams: {
        productId: null,
        subProductId: null,
        enableFlag: "0",
        quantity: 0.1,
    },
    rules: {
        subProductId: [
            { required: true, message: "物品子码不能为空", trigger: "blur" }
        ],
        quantity: [
            { required: true, message: "物品数量不能为空", trigger: "blur" },
            {   pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/,
                message: "请输入大于0的数", trigger: "blur" }
        ],
    },
})
// 表单重置
function resetLine() {
    pdLine.form = {
        productId: null,
        oldSubProductId: null,
        enableFlag: "0",
        remark: null,
        quantity: 1,
        subProductId: null,
        name: null,
    };
    proxy.resetForm("bomLineRef");
}

/** 提交按钮 */
async function submitLineForm() {
    proxy.$refs["bomLineRef"].validate(async valid => {
        debugger
        if (valid) {
            if (pdLine.operation == 1&&pd.form.productId!=null) {
                await addLine(pdLine.form).then(response => {
                    proxy.$modal.msgSuccess("新增子码成功");
                });
            } else if (pdLine.operation == 2) {
                await editLine(pdLine.form).then(response => {
                    proxy.$modal.msgSuccess("修改子码成功");
                });
            }
        }else {
            proxy.$modal.msgWarning("请完整填完信息");
            return;
        }
        pdLine.open = false;
        getBomLineList()
    })
}

/** 新增按钮操作 */
async function handleAddWmsBomLine(row) {
    resetLine();
    pdLine.form = { ...pdLine.form }
    pdLine.operation = 1
    if (pd.form.productId == null) {
        proxy.$modal.msgWarning("请先保存物品信息");
        return;
    }
    if (row != null && row.subProductId) {
        pdLine.title = "添加物料清单子码明细"
        pdLine.form.productId = row.subProductId
    }else{
        pdLine.title = "添加物料清单明细"
        if(pd.form.name==null){
            proxy.$modal.msgWarning("请先添加物品");
            return;
        }
        pdLine.form.productId = pd.form.productId
    }
    pdLine.open = true
}
/** 修改按钮操作 */
function handleEditWmsBomLine(row) {
    resetLine();
    debugger
    pdLine.form = { ...pdLine.form, ...row }
    pdLine.form.oldSubProductId = row.subProductId
    pdLine.open = true
    pdLine.title = "修改物料清单明细"
    pdLine.form.name = row.subProductId
    pdLine.operation = 2
}

/** 删除按钮操作 */
function handleDelWmsBomLine(row) {
    pdLine.operation = 3
    if(row!=null&&row.subProductId){

        const _ids = []
        _ids[0] = row.subProductId
        delWmsBomLine(_ids)
    }else{
        delWmsBomLine(pdLine.ids)
    }
}

function delWmsBomLine(ids){
    proxy.$modal.confirm('是否确认删除生产物品编号为"' +ids + '"的数据项及其子项？').then(function () {
        return delLine(ids);
    }).then(() => {
        getBomLineList()
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}


/** 查询物品物料清单明细列表 */
async function getBomLineList() {
    debugger
    pdLine.loading = true;
    pdLine.queryParams.productId = pd.form.productId
    await bomGetLineList(pdLine.queryParams).then(res => {
        if (res.data.length > 1) {
            pdLine.wmsBomLineList = proxy.handleTree(res.data, "subProductId", "productId");
        } else if (res.data.length == 0) {
            pdLine.wmsBomLineList = []
        } else {
            pdLine.wmsBomLineList[0] = res.data[0]
        }
        pdLine.loading = false;
    });
}

//下拉树结构
function getTreeselect(productId){
    bomGetLineList({ productId: productId }).then(res =>{
        pd.bomOptions = proxy.handleTree(res.rows,"subProductId","productId");
    })
}
//查询wms_product_line中的产品明细编码
async function getWmsProductLineCode(){
    await productGetList(pd.queryParams).then(response => {
    debugger
    pd.productLine = response.data
  });

}

/** 复选框选中数据 */
function handleWmsBomLineSelectionChange(selection) {
    pdLine.ids = selection.map(item => item.subProductId)
    pdLine.multiple = !selection.length;
}

const productSearchParam = reactive({
    title: "物品名称查找",
    isSingle: true,
})
function productSearchSelect(list){
    list.forEach(item => {
        pd.form.productCode = item.code
        pd.form.name = item.name
        pdLine.form.subProductId = item.id
        pdLine.form.name = item.name
    });
}

//物品子码弹窗关闭后，物品编码要变回去
var bomName = null
var bomProductCode = null
watch(() => pdLine.open, val => {
    debugger
    if(val){
       bomName = pd.form.name
       bomProductCode = pd.form.productCode
    }else{
      pd.form.name = bomName
      pd.form.productCode = bomProductCode
    }
}, { deep: true, immediate: true });

//bom_process关联
const pdBP = reactive({
    title: "",
    open: false,
    form: {},
    BomProcessList: [],
    operation: 0,
    queryParams: {
        productId: null,
    },
    rules: {
        orderNum: [
            { required: true, message: "顺序不能为空", trigger: "blur" },
            {
                pattern: /^[0-9]*[1-9][0-9]*$/,
                message: "请输入大于0的整数", trigger: "blur"
            }
        ],
        processId: [
            { required: true, message: "工序不能为空", trigger: "blur" }
        ],
        enableFlag: [
            { required: true, message: "是否启用不能为空", trigger: "blur" }
        ],
    },
});
// 表单重置
function resetBP() {
    pdBP.form = {
        id: null,
        productId: null,
        orderNum: null,
        processId: null,
        enableFlag: "0",
        remark: null,
        name: null,
        processName: null
    };
    pdBP.operation = 0;
    pdBP.title = "";
    proxy.resetForm("BomProcessRef");
}

function addBP(row) {
    resetBP();
    debugger
    pdBP.form = { ...pdBP.form, ...row };
    pdBP.form.productId = row.productId
    pdBP.title = "添加物品工序";
    pdBP.open = true;
    getBomProcessList()
}
/** 提交按钮 */
function submitBPForm() {
    proxy.$refs["BomProcessRef"].validate(async valid => {
        if (valid) {
            await addBomProcess(pdBP.form).then(res => {
                proxy.$modal.msgSuccess("新增成功");
            });
            getBomProcessList()
        }else{
            proxy.$modal.msgWarning("请完整填完信息");
        }
    });
}


/** 查询物品工序列表 */
async function getBomProcessList(){
    pdBP.loading = true;
    pdBP.queryParams.productId = pdBP.form.productId
    await listBomProcess(pdBP.queryParams).then(res=>{
        pdBP.BomProcessList = res.data
        pdBP.loading = false
    });
}


// ----------工序修改表单-----------
const pdBPLine = reactive({
    title: "",
    open: false,
    form: {},
    operation: 0,
    rules: {
        orderNum: [
            { required: true, message: "顺序不能为空", trigger: "blur" },
            {
                pattern: /^[0-9]*[1-9][0-9]*$/,
                message: "请输入大于0的整数", trigger: "blur"
            }
        ],
        processId: [
            { required: true, message: "工序不能为空", trigger: "blur" }
        ],
        enableFlag: [
            { required: true, message: "是否启用不能为空", trigger: "blur" }
        ],
    },
});
// 表单重置
function resetBPLine() {
    pdBPLine.form = {
        productId: null,
        orderNum: null,
        processId: null,
        processName: null,
        enableFlag: "0",
        remark: null,
    };
    pdBPLine.operation = 0;
    pdBPLine.title = "";
    proxy.resetForm("BomProcessLineRef");
}
/** 修改按钮 */
function handleEditBomProcessLine(row) {
    resetBPLine();
    debugger
    pdBPLine.form = { ...pdBPLine.form, ...row };
    pdBPLine.form.oldOrderNum = row.orderNum
    pdBPLine.title = "修改物品工序";
    pdBPLine.open = true;
}

/** 提交按钮 */
function submitBPLineForm() {
    proxy.$refs["BomProcessLineRef"].validate(async valid => {
        if (valid) {
            debugger
            await editBomProcess(pdBPLine.form).then(res => {
                proxy.$modal.msgSuccess("修改成功");

            });
            getBomProcessList()
            pdBPLine.open = false
        } else {
            proxy.$modal.msgWarning("请完整填完信息");
        }
    });
}

/** 删除按钮操作 */
function handleDelBomProcessLine(row) {
     proxy.$modal.confirm('是否确认删除此工序').then(function () {
        return delBomProcess(row);
    }).then(() => {
        proxy.$modal.msgSuccess("删除成功");
        getBomProcessList()
    }).catch(() => { });
}

function processSearchSelect(list) {
    list.forEach(item => {
        pdBP.form.processId = item.id
        pdBP.form.processName = item.name
        pdBPLine.form.processId = item.id
        pdBPLine.form.processName = item.name
    });
}
//工序修改弹窗关闭后，工序名称要变回去
var processName = null
var processId = null
watch(() => pdBPLine.open, val => {
    if(val){
       processName = pdBP.form.processName
       processId = pdBP.form.processId
    }else{
      pdBP.form.processName = processName
      pdBP.form.processId = processId
    }
}, { deep: true, immediate: true });

defineExpose({ add, update, del, addBP });
</script>